package com.ningxun.pagent.bus.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.ningxun.pagent.bus.domain.BusPolicyContent;
import com.ningxun.pagent.bus.mapper.BusPolicyContentMapper;
import com.ningxun.pagent.common.core.domain.entity.SysRole;
import com.ningxun.pagent.common.core.domain.model.LoginUser;
import com.ningxun.pagent.common.utils.DateUtils;
import com.ningxun.pagent.common.utils.SecurityUtils;
import com.ningxun.pagent.flow.mapper.WarmFlowMapper;
import org.dromara.warm.flow.core.FlowEngine;
import org.dromara.warm.flow.core.dto.FlowParams;
import org.dromara.warm.flow.core.entity.Instance;
import org.dromara.warm.flow.core.entity.Task;
import org.dromara.warm.flow.core.exception.FlowException;
import org.dromara.warm.flow.core.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ningxun.pagent.bus.mapper.BusPolicyApproveMapper;
import com.ningxun.pagent.bus.domain.BusPolicyApprove;
import com.ningxun.pagent.bus.service.IBusPolicyApproveService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 政策审核Service业务层处理
 * 
 * @author pagent
 * @date 2025-07-28
 */
@Service
public class BusPolicyApproveServiceImpl implements IBusPolicyApproveService 
{
    @Autowired
    private BusPolicyApproveMapper busPolicyApproveMapper;

    @Autowired
    private BusPolicyContentMapper busPolicyContentMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private WarmFlowMapper warmFlowMapper;

    /**
     * 查询政策审核
     * 
     * @param policyId 政策编号
     * @return 政策审核
     */
    @Override
    public BusPolicyApprove selectBusPolicyApproveByPolicyId(Long policyId)
    {
        return busPolicyApproveMapper.selectBusPolicyApproveByPolicyId(policyId);
    }

    /**
     * 查询政策的所有审批记录
     * 
     * @param policyId 政策编号
     * @return 审批记录列表
     */
    @Override
    public List<BusPolicyApprove> selectBusPolicyApproveListByPolicyId(Long policyId)
    {
        return busPolicyApproveMapper.selectBusPolicyApproveListByPolicyId(policyId);
    }

    /**
     * 查询政策审核列表
     * 
     * @param busPolicyContent 政策审核
     * @return 政策审核
     */
    @Override
    public List<BusPolicyContent> selectBusPolicyApproveList(BusPolicyContent busPolicyContent)
    {
        return busPolicyApproveMapper.selectBusPolicyApproveList(busPolicyContent);
    }

    /**
     * 新增政策审核
     * 
     * @param busPolicyApprove 政策审核
     * @return 结果
     */
    @Override
    public int insertBusPolicyApprove(BusPolicyApprove busPolicyApprove)
    {
        return busPolicyApproveMapper.insertBusPolicyApprove(busPolicyApprove);
    }

//    /**
//     * 修改政策审核
//     *
//     * 政策审核
//     * @return 结果
//     */
//    @Override
//    @Transactional(rollbackFor = {Exception.class})
//    public int updateBusPolicyApprove(BusPolicyContent busPolicyContent, String skipType, Long taskId,
//                                      String message, String nodeCode, String flowStatus)
//    {
//        // 设置流转参数
//        LoginUser user = SecurityUtils.getLoginUser();
//        // 是通过流程还是退回流程 【必传】
//        if (busPolicyContent.getApproveStatus() != null && busPolicyContent.getApproveStatus() == 0L) {
//            skipType = "PASS";
//        } else {
//            skipType = "REJECT";
//        }
//        FlowParams flowParams = FlowParams.build().skipType(skipType);
//        // 作为办理人保存到历史记录表 【必传】
//        flowParams.handler(user.getUser().getUserId().toString());
////        // 如果需要任意跳转流程，传入此参数  【按需传】
////        flowParams.nodeCode(nodeCode);
//        // 作为审批意见保存到历史记录表  【按需传】
//        flowParams.message(message);
//
//        // 设置办理人拥有的权限，办理中需要校验是否有权限办理 【必传】
//        List<SysRole> roles = user.getUser().getRoles();
//        List<String> permissionList = new ArrayList<>();
//        if (Objects.nonNull(roles)) {
//            permissionList = roles.stream().map(role -> "role:" + role.getRoleId()).collect(Collectors.toList());
//        }
//        permissionList.add("dept:" + SecurityUtils.getLoginUser().getUser().getDeptId());
//        permissionList.add(user.getUser().getUserId().toString());
//        flowParams.permissionFlag(permissionList);
//
//        // 验证任务是否存在
////        busPolicyContent.setType("11111111111");
////        Long definitionId = warmFlowMapper.getDefinitionIdByFlowName(busPolicyContent.getType());
////        Long taskId = warmFlowMapper.getTaskIdByDefinitionId(definitionId);
//        // Todo
//        taskId = 1400160638831038465L;
//        Task task = FlowEngine.taskService().getById(taskId);
//        if (task == null) {
//            throw new FlowException("未找到待办任务，请刷新页面重试");
//        }
//
//        // 验证任务状态
//        if (!"1".equals(task.getFlowStatus())) { // 假设"1"表示待办状态
//            throw new FlowException("任务状态不正确，可能已被处理");
//        }
//
//        // 流程变量
//        Map<String, Object> variable = new HashMap<>();
//        // 流程变量传递业务数据，按实际业务需求传递  【按需传】
//        variable.put("businessType", "busPolicyContent");
////        // 办理人表达式替换  【按需传】
//        variable.put("flag", busPolicyContent.getApproveStatus());
//        flowParams.variable(variable);
//
//        // 审核信息存入flowParams,方便查看历史审批数据  【按需传】
//        flowParams.hisTaskExt(JSON.toJSONString(busPolicyContent));
//        Instance instance = taskService.skip(taskId, flowParams);
//
//        busPolicyContent.setNodeCode(instance.getNodeCode());
//        busPolicyContent.setNodeName(instance.getNodeName());
//        busPolicyContent.setNodeType(Long.valueOf(instance.getNodeType()));
//        busPolicyContent.setFlowStatus(instance.getFlowStatus());
//
//        // 获取当前时间
//        Date nowDate = DateUtils.getNowDate();
//
//        // 封装政策内容表对象
//        busPolicyContent.setModifyTime(nowDate);
//        int contentResult = busPolicyContentMapper.updateBusPolicyContent(busPolicyContent);
//        if (contentResult <= 0) {
//            throw new RuntimeException("修改政策内容表失败");
//        }
//
////        // 封装政策审核表数据
////        BusPolicyApprove busPolicyApprove = new BusPolicyApprove();
////        busPolicyApprove.setPolicyId(busPolicyContent.getPolicyId());
////        busPolicyApprove.setApproverId(SecurityUtils.getUserId());
////        busPolicyApprove.setApproveStatus(busPolicyContent.getApproveStatus());
////        busPolicyApprove.setApproveReview(message);
////        busPolicyApprove.setApproveTime(nowDate);
////        int approveResult = busPolicyApproveMapper.updateBusPolicyApprove(busPolicyApprove);
////        if (approveResult <= 0) {
////            throw new RuntimeException("修改政策审核表失败");
////        }
//
//        return contentResult;
//    }

    /**
     * 批量删除政策审核
     * 
     * @param approveIds 需要删除的政策审核主键
     * @return 结果
     */
    @Override
    public int deleteBusPolicyApproveByApproveIds(Long[] approveIds)
    {
        return busPolicyApproveMapper.deleteBusPolicyApproveByApproveIds(approveIds);
    }

    /**
     * 删除政策审核信息
     * 
     * @param approveId 政策审核主键
     * @return 结果
     */
    @Override
    public int deleteBusPolicyApproveByApproveId(Long approveId)
    {
        return busPolicyApproveMapper.deleteBusPolicyApproveByApproveId(approveId);
    }
}
